package com.zijing2333.adaptivescheduling.SwitcherManager;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import com.zijing2333.servicerunner.IServiceRunner;

/**
 * TaskRunnerConnectionManager 类负责管理与 IServiceRunner 服务的连接。
 */
public class TaskRunnerConnectionManager {
    private static final String TAG = TaskRunnerConnectionManager.class.getSimpleName();

    private Context switcherContext;
    private IServiceRunner mSwitcherService;

    /**
     * 构造方法，初始化并连接到服务。
     *
     * @param context 上下文
     */
    public TaskRunnerConnectionManager(Context context) {
        switcherContext = context;
        connectToService();
    }

    /**
     * 获取与 IServiceRunner 服务的连接。
     *
     * @return IServiceRunner 服务实例
     */
    public IServiceRunner getSwitcherService() {
        return mSwitcherService;
    }

    /**
     * 连接到 IServiceRunner 服务。
     */
    private void connectToService() {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.zijing2333.servicerunner", "com.zijing2333.servicerunner.JSRuntimeService"));
        boolean result = switcherContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

        if (!result) {
            Log.e(TAG, "Failed to bind to IServiceRunner service");
        }
    }

    /**
     * 与 IServiceRunner 服务断开连接。
     */
    public void disconnectFromService() {
        if (mSwitcherService != null) {
            switcherContext.unbindService(mConnection);
            mSwitcherService = null;
        }
    }

    /**
     * 用于管理与 IServiceRunner 服务的连接的 ServiceConnection 实例。
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mSwitcherService = IServiceRunner.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mSwitcherService = null;
        }
    };
}
